// 文章相关的请求

import { ApiResponse, ArticleDetail, Comment, CommentRes } from '@/types/data'
import { RootAction, RootThunkAction } from '@/types/store'
import http from '@/utils/request'

// 文章详情
export function getArticleInfo(id: string): RootThunkAction {
  return async (dispatch) => {
    const res = await http.get<ApiResponse<ArticleDetail>>(`articles/${id}`)
    console.log('文章详情', res)

    dispatch({
      type: 'article/set_info',
      payload: res.data.data,
    } as RootAction)
  }
}

// 文章全部评论
export function getAllComment(
  id: string,
  offset?: string,
  limit: number = 10
): RootThunkAction {
  return async (dispatch) => {
    const res = await http.get<ApiResponse<CommentRes>>('/comments', {
      params: {
        type: 'a', // 仅获取文章评论
        source: id,
        offset,
        limit,
      },
    })

    console.log('获取评论', res)
    dispatch({
      type: 'article/set_all_commnet',
      payload: res.data.data,
    } as RootAction)
  }
}

// 点赞 取消点赞
export function likeAritcle(id: string, attitude: number): RootThunkAction {
  return async (dispatch) => {
    if (attitude === 1) {
      await http.delete(`/article/likings/${id}`)
    } else {
      await http.post('/article/likings', {
        target: id,
      })
    }

    //重兴获取文章详情
    dispatch(getArticleInfo(id))
  }
}

// 收藏, 取消收藏
export function collectAritcle(
  id: string,
  is_collected: boolean
): RootThunkAction {
  return async (dispatch) => {
    if (is_collected) {
      await http.delete(`/article/collections/${id}`)
    } else {
      await http.post('/article/collections', {
        target: id,
      })
    }

    //重兴获取文章详情
    dispatch(getArticleInfo(id))
  }
}

// 关注作者
export function followAuthor(
  id: string, // 作者id
  is_followed: boolean //关注状态
): RootThunkAction {
  return async (dispatch, getState) => {
    if (is_followed) {
      // 取消关注
      await http.delete(`/user/followings/${id}`)
    } else {
      await http.post('/user/followings', {
        target: id,
      })
    }

    //重兴获取文章详情
    dispatch(getArticleInfo(getState().aticle.info.art_id))
  }
}

// 评论文章
export function publishContent(val: string, id: string): RootThunkAction {
  return async (dispatch, getState) => {
    const res = await http.post<
      ApiResponse<{
        com_id: string
        target: string
        new_obj: Comment
      }>
    >('/comments', {
      target: id,
      content: val,
    })

    console.log('评论', res)
    dispatch({
      type: 'article/save_new_commnet',
      payload: res.data.data.new_obj,
    } as RootAction)
  }
}
